import io
import json
import os
import shutil
import base64
import imghdr

import base64
import io
import os
import os.path
import sys
import time
from ast import literal_eval

from PIL import Image
from PIL import ImageFile

base_path = 'server/database/resource/img/'


# 获取base_path
def get_base_path():
    return base_path


# 获取图片数据的格式
def get_image_format(image_data):
    image_format = imghdr.what(None, image_data)
    return image_format


# 压缩base64的图片
def compress_image_bs4(b64, fm, mb=190, k=0.8):
    """不改变图片尺寸压缩到指定大小
    :param outfile: 压缩文件保存地址
    :param mb: 压缩目标，KB
    :param step: 每次调整的压缩比率
    :param quality: 初始压缩比率
    :return: 压缩文件地址，压缩文件大小
    """

    f = base64.b64decode(b64)
    with io.BytesIO(f) as im:
        o_size = len(im.getvalue()) // 1024
        if o_size <= mb:
            return b64
        im_out = im

        while o_size > mb:
            img = Image.open(im_out)
            x, y = img.size
            out = img.resize((int(x * k), int(y * k)), Image.ANTIALIAS)
            im_out.close()
            im_out = io.BytesIO()
            out.save(im_out, fm)
            o_size = len(im_out.getvalue()) // 1024
        b64 = base64.b64encode(im_out.getvalue())
        im_out.close()
        return str(b64, encoding='utf8')


# 将文件转化成适用于前端的base64格式
def file_to_base64(file_path, quality=1):
    file_path = base_path + file_path
    with open(file_path, 'rb') as file:
        binary_data = file.read()
        img_format = get_image_format(binary_data)
        base64_data = base64.b64encode(binary_data).decode('utf-8')
        if quality != 1:
            base64_data = compress_image_bs4(base64_data, img_format, 100, quality)
        res = 'data:image/' + img_format + ';base64,' + base64_data
        return res


# 将前端的base64字符串转化为文件并存储
def save_base64_as_file(base64_string, file_path, img_name):
    file_path = base_path + file_path
    # print(file_path)
    # print(img_name)
    # 去除前端图片类型信息
    base64_data = base64_string.split(',')[1]
    # 创建名为 gid 的目录（如果不存在）
    if not os.path.exists(file_path):
        os.makedirs(file_path)

    # 解码 base64 字符串为二进制数据
    binary_data = base64.b64decode(base64_data)

    # 将二进制数据保存到 gid 目录中的文件中
    with open(f'{file_path}{img_name}', 'wb') as file:
        file.write(binary_data)

    return file_path + img_name, base_path


# 保存文件
def save_file(file_path, file_name, data):
    file_path = base_path + file_path
    # 创建名为file_path 的目录（如果不存在）
    if not os.path.exists(file_path):
        os.makedirs(file_path)
    # 保存数据
    with open(f'{file_path}{file_name}', 'wb') as file:
        file.write(data.encode())

    return file_path + file_name


# 删除某个文件夹下的所有文件
def del_directory(path):
    directory_path = base_path + path

    if not os.path.exists(directory_path):
        print(f"目录'{directory_path}'不存在")
        return f"目录'{directory_path}'不存在"

    if not os.path.isdir(directory_path):
        print(f"'{directory_path}'不是一个目录")
        return f"'{directory_path}'不是一个目录"
    shutil.rmtree(directory_path)
    print(f"目录'{directory_path}'已删除")

    # # 仅删除目录下文件
    # for filename in os.listdir(directory_path):
    #     file_path = os.path.join(directory_path, filename)
    #     try:
    #         # 尝试删除文件
    #         if os.path.isfile(file_path) or os.path.islink(file_path):
    #             os.unlink(file_path)
    #         elif os.path.isdir(file_path):
    #             shutil.rmtree(file_path)
    #     except Exception as e:
    #         print(f"删除文件'{file_path}'出错: {e}")
    #         return f"删除文件'{file_path}'出错: {e}"
    return True


data_path = 'server/database/resource/data'


# 获取文件夹下文件数量
def getDirCount(path=data_path):

    return len([d for d in os.listdir(path) if os.path.isdir(os.path.join(path, d))])


# 获取某页gid集合
def getPageGids(page, pageSize):
    # 获取当前目录下的所有文件夹名字
    folder_names = [d for d in os.listdir(data_path) if os.path.isdir(os.path.join(data_path, d))]

    # 对文件夹名字进行分组，每组五个
    grouped_folder_names = [folder_names[i:i + pageSize] for i in range(0, len(folder_names), pageSize)]

    return grouped_folder_names[page]


# 将json文件转化成字典格式
def readJSFile(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        data = json.load(file)

    # 将字符串转换为Python对象
    def string_to_object(data):
        if isinstance(data, str):
            try:
                data = literal_eval(data)
            except (ValueError, SyntaxError):
                pass  # 如果字符串不是有效的Python表达式，保持它为字符串
        elif isinstance(data, list):
            for i in range(len(data)):
                data[i] = string_to_object(data[i])
        elif isinstance(data, dict):
            for key in data:
                data[key] = string_to_object(data[key])
        return data

    # 转换JSON中的字符串
    converted_data = string_to_object(data)
    return converted_data


# 将字典保存到文件中
def writeToJSFile(data, file_path):
    with open(file_path, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=4)

# # 示例 base64 字符串
# base64_string = ""
# gid = '1/5/'
#
# save_base64_as_file(base64_string, gid, 'img1.jpg')

# base64_string = ""

# # # 要转换的文件路径
# file_path = '1/1/background.jpg'
#
# # 将文件转换为 base64 字符串
# base64_string = file_to_base64(file_path)
#
# print(base64_string)

# path = '1' + '/' + '21'
# del_directory(path)
